﻿using AntdUI;
using ImportPlcPointPosition.Core;
using ImportPlcPointPosition.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZR.Model.Models.ProductionControl;

namespace ImportPlcPointPosition.Controls
{
    public partial class TechnicalFlowPage : BaseUserControl
    {
        /// <summary>
        /// 工艺路线
        /// </summary>
        public TechnicalFlowPage()
        {
            InitializeComponent();
            this.Load += TechniqueRoadPage_Load;
        }
        BindingList<CksTechnicalFlowNodes> Source = new BindingList<CksTechnicalFlowNodes>();
        BindingList<CksPlcActions> ActionsSource = new BindingList<CksPlcActions>();
        BindingList<CksValidationField> ValidationFields = new BindingList<CksValidationField>();
        CksTechnicalFlowNodes Context = null;
        private void TechniqueRoadPage_Load(object sender, EventArgs e)
        {
            InitData();
            InitTable();
            InitActionTable();
            InitValidationFieldTable();
            ReflushData();
        }

        private void InitData()
        {
            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksVirtualTable>()
                   .OrderBy(a => a.Sequence)
                   .ToList();
            CellButtonHelper.Tables = lst;
            List<ISelectItem> items = new List<ISelectItem>();
            foreach (var t in lst)
            {
                items.Add(new AntdUI.SelectItem(t.TableName, t.Id));
            }
            CellButtonHelper.TableDropDownItems = items.ToArray();
        }

        private void InitTable()
        {
            table1.EditMode = TEditMode.Click;
            table1.Columns = new ColumnCollection();
            table1.Columns.Add(new Column("NodeId", "节点编号"));
            table1.Columns.Add(new Column("Notes", "说明"));
            // table1.Columns.Add(new Column("TableId", "表ID"));
            table1.Columns.Add(new Column("TableItem", "数据表")); // 采用下拉选择
            table1.Columns.Add(new ColumnCheck("AllowReprocess", "是否允许重复加工"));
            table1.Columns.Add(new ColumnCheck("AllowOkReprocess", "是否允许OK件重复加工"));
            table1.Columns.Add(new ColumnCheck("RequireOk", "结果是否必须OK"));
            table1.Columns.Add(new Column("PreNodeId", "前置节点编号"));
            table1.Columns.Add(new ColumnCheck("NeedPrevCheck", "是否验证前置节点"));
            table1.Columns.Add(new ColumnCheck("Nullity", "禁用"));
            table1.Bordered = true;
            table1.EnableHeaderResizing = true;
            table1.EmptyHeader = true;
            table1.Gap = 6;
            table1.VisibleHeader = true;

            table1.Binding(Source);
            table1.CellBeginEditInputStyle += (s, e) =>
            {
                e.Input.SelectAll();
            };
            table1.CellClick += Table1_CellClick;
        }

        private void Table1_CellClick(object sender, TableClickEventArgs e)
        {
            var config = e.Record as CksTechnicalFlowNodes;
            Context = config;
            if (e.Button == MouseButtons.Left)
            {
                LoadActionData(Context);
            }
        }

        private void InitActionTable()
        {
            table3.EditMode = TEditMode.Click;
            table3.Columns = new ColumnCollection();

            table3.Columns.Add(new Column("PlcId", "PlcId") { });
            table3.Columns.Add(new Column("ActionId", "动作"));
            table3.Columns.Add(new Column("ReadDB", "ReadDB"));
            table3.Columns.Add(new Column("WriteDB", "WriteDB"));


            table3.Bordered = true;
            table3.EnableHeaderResizing = true;
            table3.EmptyHeader = true;
            table3.Gap = 6;
            table3.VisibleHeader = true;
            table3.CellBeginEditInputStyle += (s, e) =>
            {
                e.Input.SelectAll();
            };
            table3.SelectIndexChanged += Table3_SelectIndexChanged;

        }

        private void InitValidationFieldTable()
        {
            table2.EditMode = TEditMode.Click;
            table2.Columns = new ColumnCollection();
            table2.Columns.Add(new Column("Sequence", "验证顺序"));
            table2.Columns.Add(new Column("Notes", "说明") { });
            table2.Columns.Add(new Column("DataId", "DataId"));
            table2.Columns.Add(new ColumnCheck("IsPrimary", "是否主码"));
            //table2.Columns.Add(new ColumnCheck("IsResult", "是否结果"));

            table2.Bordered = true;
            table2.EnableHeaderResizing = true;
            table2.EmptyHeader = true;
            table2.Gap = 6;
            table2.VisibleHeader = true;
            table2.CellBeginEditInputStyle += (s, e) =>
            {
                e.Input.SelectAll();
            };
          

        }


        private void Table3_SelectIndexChanged(object sender, EventArgs e)
        {

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Source.Add(new CksTechnicalFlowNodes() { });
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {

            var result = MessageBoxWarn("删除警告", "确认要删除吗");
            if (result != DialogResult.OK)
                return;
            if (table1.SelectedIndex < 0)
                return;
            var db = SqlSugarHelper.MesDB;
            var row = Source[table1.SelectedIndex - 1];

            //删除动作
            db.Deleteable<CksPlcActions>().Where(a => a.ActionType == 2 && a.BusinessId == row.Id).ExecuteCommand();
            db.Deleteable<CksValidationField>().Where(a =>  a.BusinessId == row.Id).ExecuteCommand();
            db.Deleteable(row).ExecuteCommand();
            Source.Remove(row);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (HasDuplicateProperty(Source.ToList(), (a) => a.TableId))
            {
                MessageError("表格配置重复");
                return;
            }
            if (HasDuplicateProperty(Source.ToList(), (a) => a.NodeId))
            {
                MessageError("节点编号不允许重复");
                return;
            }
            var items = Source.ToList().OrderBy(a => a.NodeId).ToList();




            var db = SqlSugarHelper.MesDB;
            foreach (var item in items)
            {

                if (item.Id == 0)
                    db.Insertable(item).ExecuteCommand();
                else
                    db.Updateable(item).ExecuteCommand();
            }
            ReflushData();
            MessageInfo("OK");
        }


        public bool HasDuplicateProperty<T, TProp>(List<T> list, Func<T, TProp> selector)
        {
            var set = new HashSet<TProp>();
            foreach (var item in list)
            {
                if (!set.Add(selector(item)))
                {
                    return true;
                }
            }
            return false;
        }

        private void ReflushData()
        {
            InitData();
            Source.Clear();

            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksTechnicalFlowNodes>()
                   .OrderBy(a => a.NodeId)
                   .ToList();
            foreach (var item in lst)
            {
                Source.Add(item);
            }
            if (Source.Count > 0)
            {
                table1.SelectedIndex = 1;
                Context = Source[0];
                LoadActionData(Context);
            }
            else
            {
                table1.SelectedIndex = -1;
                Context = null;
                ActionsSource.Clear();
            }
        }

        private void LoadActionData(CksTechnicalFlowNodes context)
        {
            ActionsSource.Clear();
            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksPlcActions>().Where(a => a.ActionType == 2 && a.BusinessId == context.Id).OrderBy(a => a.Id).ToList();
            foreach (var item in lst)
            {
                ActionsSource.Add(item);
            }
            this.table3.Binding(ActionsSource);

            LoadValidationFields(context);
        }


        private void LoadValidationFields(CksTechnicalFlowNodes context)
        {
            ValidationFields.Clear();
            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksValidationField>().Where(a =>  a.BusinessId == context.Id).OrderBy(a => a.Sequence).ToList();
            foreach (var item in lst)
            {
                ValidationFields.Add(item);
            }
            this.table2.Binding(ValidationFields);

        }


        private void btnImport_Click(object sender, EventArgs e)
        {

            if (CellButtonHelper.Tables.Count == 0)
            {
                MessageError("请先配置采集表");
                return;
            }
            var result = MessageBoxWarn("警告", "从虚拟表提取数据,是否继续");
            if (result == DialogResult.OK)
            {
                InitData();
                foreach (var item in CellButtonHelper.Tables)
                {
                    var one = Source.ToList().Find(a => a.TableId == item.Id);
                    if (one == null)
                        Source.Add(new CksTechnicalFlowNodes() { TableId = item.Id, Notes = item.Notes });
                }
            }
        }

        private void btnLoadData_Click(object sender, EventArgs e)
        {
            ReflushData();
        }

        private void btnAddAction_Click(object sender, EventArgs e)
        {
            ActionsSource.Add(new CksPlcActions() { });
        }

        private void btnSaveActions_Click(object sender, EventArgs e)
        {
            if (Context == null) return;
            var items = ActionsSource.ToList().OrderBy(a => a.ActionId).ToList();
            var db = SqlSugarHelper.MesDB;
            foreach (var item in items)
            {
                item.BusinessId = Context.Id;
                item.ActionType = 2;
                item.Name = "工艺路线";
                if (item.Id == 0)
                    db.Insertable(item).ExecuteCommand();
                else
                    db.Updateable(item).ExecuteCommand();
            }
            LoadActionData(Context);
            MessageInfo("OK");
        }

        private void btnDelAction_Click(object sender, EventArgs e)
        {
            if (table3.SelectedIndex < 0 || table3.SelectedIndex > ActionsSource.Count)
            {
                MessageError("未选择数据");
                return;
            }
            var result = MessageBoxWarn("删除警告", "确认要删除吗");
            if (result != DialogResult.OK)
                return;

            var db = SqlSugarHelper.MesDB;
            var row = ActionsSource[table3.SelectedIndex - 1];
            db.Deleteable(row).ExecuteCommand();
            ActionsSource.Remove(row);
        }

        private void btnAddValidationField_Click(object sender, EventArgs e)
        {
            ValidationFields.Add(new CksValidationField() { });
        }

        private void btnSaveValidationField_Click(object sender, EventArgs e)
        {
            if (Context == null) return;
            var items = ValidationFields.ToList().OrderBy(a => a.Sequence).ToList();
            var db = SqlSugarHelper.MesDB;
            foreach (var item in items)
            {
                item.BusinessId = Context.Id;
                
              
                if (item.Id == 0)
                    db.Insertable(item).ExecuteCommand();
                else
                    db.Updateable(item).ExecuteCommand();
            }
            LoadActionData(Context);
            MessageInfo("OK");
        }

        private void btnDeleteValidationField_Click(object sender, EventArgs e)
        {
            if (table2.SelectedIndex < 0 || table2.SelectedIndex > ValidationFields.Count)
            {
                MessageError("未选择数据");
                return;
            }
            var result = MessageBoxWarn("删除警告", "确认要删除吗");
            if (result != DialogResult.OK)
                return;

            var db = SqlSugarHelper.MesDB;
            var row = ValidationFields[table2.SelectedIndex - 1];
            db.Deleteable(row).ExecuteCommand();
            ValidationFields.Remove(row);
        }
    }
}
